package com.framework.network.interceptor.urlinter

import android.text.TextUtils
import okhttp3.HttpUrl
import java.util.*

/**
 * ================================================
 * 域名解析器, 此解析器用来解析域名, 默认将您的域名作为 BaseUrl, 只会将旧 URL 地址中的域名替换成你想要的地址
 * 比如:
 * 1.
 * 旧 URL 地址为 https://www.github.com/wiki, 您调用 {@link ApiUrlManager#putDomain(String, String)}
 * 方法传入的 URL 地址是 https://www.google.com/api, 经过本解析器解析后生成的新 URL 地址为 http://www.google.com/api/wiki
 * 2.
 * 旧 URL 地址为 https://www.github.com/wiki, 您调用 {@link ApiUrlManager#putDomain(String, String)}
 * 方法传入的 URL 地址是 https://www.google.com, 经过本解析器解析后生成的新 URL 地址为 http://www.google.com/wiki
 *
 * @see UrlParser
 * ================================================
 */
class DomainUrlParser : UrlParser {
    private var mCache: CacheUtils<String, String>? = null
    
    override fun parseUrl(domainUrl: HttpUrl, url: HttpUrl): HttpUrl {
        if (null == domainUrl) return url
        
        val builder = url.newBuilder()
        if (mCache?.get(getKey(domainUrl, url)).isNullOrBlank()) {
            for (i in 0 until url.pathSize) {
                builder.removePathSegment(0)
            }
            
            val newPathSegments = ArrayList<String>()
            newPathSegments.addAll(domainUrl.encodedPathSegments)
            newPathSegments.addAll(url.encodedPathSegments)
            
            for (PathSegment in newPathSegments) {
                builder.addEncodedPathSegment(PathSegment)
            }
        } else {
            mCache?.get(getKey(domainUrl, url))?.let { builder.encodedPath(it) }
        }
        
        val httpUrl = builder
            .scheme(domainUrl.scheme)
            .host(domainUrl.host)
            .port(domainUrl.port)
            .build()
        
        if (TextUtils.isEmpty(mCache?.get(getKey(domainUrl, url)))) {
            mCache?.put(getKey(domainUrl, url), httpUrl.encodedPath)
        }
        return httpUrl
    }
    
    private fun getKey(domainUrl: HttpUrl, url: HttpUrl): String {
        return domainUrl.encodedPath + url.encodedPath
    }
}